// @/components/knowledge-base/index.jsx
import React, { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";

import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/components/ui/use-toast";
import {
  Brain,
  FileText,
  CheckSquare,
  AlertTriangle,
  Shield,
  ThumbsDown,
  Settings,
  RefreshCw,
  Zap
} from "lucide-react";

// API 导入
import { SafetyRiskPointAPI } from "@/api/SafetyRiskPoint";
import { EmergencyMeasureTemplateAPI } from "@/api/EmergencyMeasureTemplate";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";
import { StandardAPI } from "@/api/Standard";
import { QualityIssueTemplateAPI } from "@/api/QualityIssueTemplate";
import { enhanceKnowledgeBase } from "@/api/functions";

// 组件导入
import KnowledgeOverview from "../components/knowledge-base/KnowledgeOverview"; // 知识概览总览组件
import MethodTemplates from "@/components/knowledge-base/components/MethodTemplates";
import Standards from "@/components/knowledge-base/components/Standards";
import SafetyRisks from "@/components/knowledge-base/components/SafetyRisks";
import EmergencyMeasureTemplateManager from "../components/knowledge-base/EmergencyMeasureTemplateManager"; // 应急措施管理组件
import SpecParameters from "@/components/knowledge-base/components/SpecParameters";

// 工具函数导入
import { apiCallWithRetry } from "@/utils/api-utils";

export default function KnowledgeBase() {
  // 数据状态
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [standards, setStandards] = useState([]);
  const [riskPoints, setRiskPoints] = useState([]);
  const [emergencyMeasureTemplates, setEmergencyMeasureTemplates] = useState(
    []
  );
  const [qualityIssueTemplates, setQualityIssueTemplates] = useState([]);

  // 加载/错误状态
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [retryCount, setRetryCount] = useState(0);

  // 搜索/筛选条件
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedScenario, setSelectedScenario] = useState("all");
  const { toast } = useToast();

  // 其他状态
  const [isEnhancing, setIsEnhancing] = useState(false);
  const [activeTab, setActiveTab] = useState("overview");
  const [filteredCounts, setFilteredCounts] = useState({
    methods: 0,
    standards: 0,
    risks: 0,
    emergencyMeasures: 0,
    qualityIssues: 0,
  });

  // 初始化 - 从URL hash获取标签页
  useEffect(() => {
    const hash = window.location.hash;
    if (hash === "#specs") {
      setActiveTab("specs");
      window.history.replaceState(null, null, window.location.pathname);
    }
  }, []);

  // 加载所有知识库数据
  const loadKnowledgeData = async (isRetry = false) => {
    if (!isRetry) {
      setIsLoading(true);
      setError(null);
    }

    try {
      const [
        methodTemplatesData,
        standardsData,
        riskPointsData,
        emergencyMeasureTemplatesData,
        qualityIssuesData,
      ] = await Promise.all([
        apiCallWithRetry(() =>
          ConstructionMethodTemplateAPI.getList({ sort: "-createdDate" })
        ),
        apiCallWithRetry(() => StandardAPI.getList({ sort: "-createdDate" })),
        apiCallWithRetry(() =>
          SafetyRiskPointAPI.getList({ sort: "-createdDate" })
        ),
        apiCallWithRetry(() =>
          EmergencyMeasureTemplateAPI.getList({ sort: "-createdDate" })
        ),
        apiCallWithRetry(() =>
          QualityIssueTemplateAPI.getList({ sort: "-createdDate" })
        ),
      ]);

      // 数据格式校验
      const methodTemplatesArray = Array.isArray(methodTemplatesData.data)
        ? methodTemplatesData.data
        : [];

      const standardsArray = Array.isArray(standardsData.data)
        ? standardsData.data
        : [];

      const riskPointsArray = Array.isArray(riskPointsData.data)
        ? riskPointsData.data
        : [];

      const emergencyMeasureTemplatesArray = Array.isArray(
        emergencyMeasureTemplatesData.data
      )
        ? emergencyMeasureTemplatesData.data
        : [];

      const qualityIssuesArray = Array.isArray(qualityIssuesData.data)
        ? qualityIssuesData.data
        : [];

      // 更新状态
      setMethodTemplates(methodTemplatesArray);
      setStandards(standardsArray);
      setRiskPoints(riskPointsArray);
      setEmergencyMeasureTemplates(emergencyMeasureTemplatesArray);
      setQualityIssueTemplates(qualityIssuesArray);

      // 重置错误和重试次数
      setError(null);
      setRetryCount(0);

      // 更新计数
      handleFilteredCountChange("methods", methodTemplatesArray.length);
      handleFilteredCountChange("standards", standardsArray.length);
      handleFilteredCountChange("risks", riskPointsArray.length);
      handleFilteredCountChange(
        "emergencyMeasures",
        emergencyMeasureTemplatesArray.length
      );
      handleFilteredCountChange("qualityIssues", qualityIssuesArray.length);
    } catch (error) {
      console.error("加载知识库数据失败:", error);

      const isRateLimitError =
        error.message?.includes("429") ||
        error.message?.includes("Rate limit") ||
        (error.response && error.response.status === 429);

      if (isRateLimitError) {
        setError({
          type: "rate_limit",
          message: "请求过于频繁，请稍后再试",
          canRetry: true,
        });
      } else {
        setError({
          type: "general",
          message: error.message || "加载数据时发生未知错误",
          canRetry: true,
        });
      }

      if (!isRetry) {
        setMethodTemplates([]);
        setStandards([]);
        setRiskPoints([]);
        setEmergencyMeasureTemplates([]);
        setQualityIssueTemplates([]);
        handleFilteredCountChange("methods", 0);
        handleFilteredCountChange("standards", 0);
        handleFilteredCountChange("risks", 0);
        handleFilteredCountChange("emergencyMeasures", 0);
        handleFilteredCountChange("qualityIssues", 0);
      }
    }

    setIsLoading(false);
  };

  // 初始化加载数据
  useEffect(() => {
    loadKnowledgeData();
  }, []);

  // 处理筛选计数变化
  const handleFilteredCountChange = useCallback((type, count) => {
    setFilteredCounts((prev) => ({ ...prev, [type]: count }));
  }, []);

  // 重试加载数据
  const handleRetry = () => {
    setRetryCount((prev) => prev + 1);
    loadKnowledgeData(true);
  };

  // 施工方法模板提交
  const handleMethodTemplateSubmit = async (templateData) => {
    try {
      if (templateData.id) {
        await ConstructionMethodTemplateAPI.update(
          templateData.id,
          templateData
        );
      } else {
        await ConstructionMethodTemplateAPI.create(templateData);
      }
      await loadKnowledgeData();
      return true;
    } catch (error) {
      console.error("保存模板失败:", error);
      alert("保存模板失败: " + (error.message || "未知错误"));
      return false;
    }
  };

  // 复制施工方法模板
  const handleCopyMethodTemplate = async (templateData) => {
    try {
      const copiedData = {
        ...templateData,
        methodName: `${templateData.methodName}（副本）`,
        constructionSteps: templateData.constructionSteps?.map((step) => {
          const { id, templateId, ...rest } = step;
          return rest;
        }),
      };
      delete copiedData.id;
      delete copiedData.createdDate;
      delete copiedData.updatedDate;

      await ConstructionMethodTemplateAPI.create(copiedData);
      toast({
        title: "复制成功！",
        description: `模板${templateData.methodName}已成功复制`,
      });
      await loadKnowledgeData();
    } catch (error) {
      console.error("复制模板失败:", error);
      alert("复制模板失败: " + (error.message || "未知错误"));
    }
  };

  // 删除施工方法模板
  const handleDeleteMethodTemplate = async (templateId) => {
    if (window.confirm("确定要删除此施工方法模板吗？此操作无法撤销。")) {
      try {
        await ConstructionMethodTemplateAPI.delete(templateId);
        await loadKnowledgeData();
      } catch (error) {
        console.error("删除模板失败:", error);
        alert("删除模板失败，请稍后重试。");
      }
    }
  };

  // AI增强知识库模板
  const handleEnhanceKnowledge = async (templateId) => {
    setIsEnhancing(true);
    try {
      const response = await enhanceKnowledgeBase({ template_id: templateId });
      if (response && response.data && response.data.success) {
        alert(`新版本创建成功！`);
        await loadKnowledgeData();
      } else {
        alert("创建新版本失败: " + (response?.data?.error || "未知错误"));
      }
    } catch (error) {
      console.error("创建新版本失败:", error);
      alert("创建新版本失败，请重试");
    } finally {
      setIsEnhancing(false);
    }
  };

  // 标准规范提交
  const handleSaveStandard = async (standardData) => {
    try {
      if (standardData.id) {
        await StandardAPI.update(standardData.id, standardData);
      } else {
        await StandardAPI.create(standardData);
      }
      await loadKnowledgeData();
      return true;
    } catch (error) {
      console.error("保存标准失败:", error);
      alert("保存标准失败: " + (error.message || "未知错误"));
      return false;
    }
  };

  // 删除标准规范
  const handleDeleteStandard = async (standardId) => {
    if (window.confirm("确定要删除此标准规范吗？此操作无法撤销。")) {
      try {
        await StandardAPI.delete(standardId);
        await loadKnowledgeData();
      } catch (error) {
        console.error("删除标准失败:", error);
        alert("删除标准失败，请稍后重试。");
      }
    }
  };

  // 安全危险点处理函数
  const handleSaveRiskPoint = async (riskPointData) => {
    try {
      if (riskPointData.id) {
        await SafetyRiskPointAPI.update(riskPointData.id, riskPointData);
      } else {
        await SafetyRiskPointAPI.create(riskPointData);
      }
      await loadKnowledgeData();
    } catch (error) {
      console.error("保存危险点失败:", error);
      alert("保存危险点失败: " + (error.message || "未知错误"));
    }
  };

  const handleDeleteRiskPoint = async (riskPointId) => {
    if (window.confirm("确定要删除此危险点吗？")) {
      try {
        await SafetyRiskPointAPI.delete(riskPointId);
        await loadKnowledgeData();
      } catch (error) {
        console.error("删除危险点失败:", error);
        alert("删除危险点失败，请稍后重试。");
      }
    }
  };

  // 应急措施处理函数
  const handleSaveEmergencyMeasureTemplate = async (data) => {
    try {
      if (data.id) {
        await EmergencyMeasureTemplateAPI.update(data.id, data);
      } else {
        await EmergencyMeasureTemplateAPI.create(data);
      }
      await loadKnowledgeData();
    } catch (error) {
      console.error("保存应急措施模板失败:", error);
      alert("保存应急措施模板失败: " + (error.message || "未知错误"));
    }
  };

  const handleDeleteEmergencyMeasureTemplate = async (id) => {
    if (window.confirm("确定要删除此应急措施模板吗？")) {
      try {
        await EmergencyMeasureTemplateAPI.delete(id);
        await loadKnowledgeData();
      } catch (error) {
        console.error("删除应急措施模板失败:", error);
        alert("删除应急措施模板失败，请稍后重试。");
      }
    }
  };

  // 计数变化回调
  const handleRisksFilteredCountChange = useCallback(
    (count) => {
      handleFilteredCountChange("risks", count);
    },
    [handleFilteredCountChange]
  );

  const handleEmergencyMeasuresCountChange = useCallback(
    (count) => {
      handleFilteredCountChange("emergencyMeasures", count);
    },
    [handleFilteredCountChange]
  );

  // 渲染错误提示
  const renderError = () => (
    <div className="max-w-2xl mx-auto mt-12">
      <Alert className="border-red-200 bg-red-50">
        <AlertTriangle className="h-4 w-4 text-red-600" />
        <AlertDescription className="text-red-800">
          <div className="space-y-3">
            <p className="font-medium">数据加载失败</p>
            <p>{error.message}</p>
            {error.type === "rate_limit" && (
              <p className="text-sm">
                这通常是由于请求过于频繁导致的。请等待几秒钟后重试，或刷新页面。
              </p>
            )}
            <div className="flex gap-2">
              <Button
                onClick={handleRetry}
                size="sm"
                variant="outline"
                className="border-red-300 text-red-700 hover:bg-red-100"
              >
                <RefreshCw className="w-4 h-4 mr-1" />
                重试 {retryCount > 0 && `(${retryCount})`}
              </Button>
              <Button
                onClick={() => window.location.reload()}
                size="sm"
                variant="outline"
                className="border-red-300 text-red-700 hover:bg-red-100"
              >
                刷新页面
              </Button>
            </div>
          </div>
        </AlertDescription>
      </Alert>
    </div>
  );

  // 加载中状态
  if (isLoading) {
    return (
      <div className="p-6 text-center min-h-screen flex flex-col items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-600 mx-auto mb-4"></div>
        <p className="text-gray-700 text-lg">加载知识库中...</p>
        {retryCount > 0 && (
          <p className="text-sm text-gray-500 mt-2">重试次数: {retryCount}</p>
        )}
      </div>
    );
  }

  // 全局错误状态
  if (
    error &&
    methodTemplates.length === 0 &&
    standards.length === 0 &&
    riskPoints.length === 0 &&
    emergencyMeasureTemplates.length === 0 &&
    qualityIssueTemplates.length === 0
  ) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-7xl mx-auto p-6">
          <div className="mb-6">
            <h1 className="text-2xl font-bold text-gray-900 mb-2 flex items-center gap-2">
              <Brain className="w-6 h-6 text-blue-600" />
              施工方法知识库
            </h1>
            <p className="text-gray-600">
              管理标准化施工方法模板、标准规范，为方案生成提供专业知识支持
            </p>
          </div>
          {renderError()}
        </div>
      </div>
    );
  }

  // 主渲染
  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto p-6">
        <div className="mt-6">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
            <div>
              <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
                施工方法知识库
              </h1>
              <p className="text-gray-600 mt-1">
                管理标准化施工方法模板、标准规范，为方案生成提供专业知识支持
              </p>
            </div>
          </div>
        </div>

        {/* 部分数据加载失败提示 */}
        {error &&
          (methodTemplates.length > 0 ||
            standards.length > 0 ||
            riskPoints.length > 0 ||
            emergencyMeasureTemplates.length > 0 ||
            qualityIssueTemplates.length > 0) && (
            <Alert className="mb-6 border-yellow-200 bg-yellow-50">
              <AlertTriangle className="h-4 w-4 text-yellow-600" />
              <AlertDescription className="text-yellow-800">
                <div className="flex items-center justify-between">
                  <span>部分数据可能未能完全加载，显示的信息可能不完整。</span>
                  <Button
                    onClick={handleRetry}
                    size="sm"
                    variant="outline"
                    className="border-yellow-300 text-yellow-700 hover:bg-yellow-100"
                  >
                    <RefreshCw className="w-4 h-4 mr-1" />
                    重新加载
                  </Button>
                </div>
              </AlertDescription>
            </Alert>
          )}

        {/* 标签页切换 */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-6">
            <TabsTrigger value="overview">
              <Brain className="w-4 h-4 mr-2" />
              知识概览
            </TabsTrigger>
            <TabsTrigger value="methods">
              <FileText className="w-4 h-4 mr-2" />
              方法模板 ({filteredCounts.methods})
            </TabsTrigger>
            <TabsTrigger value="standards">
              <CheckSquare className="w-4 h-4 mr-2" />
              标准规范 ({filteredCounts.standards})
            </TabsTrigger>
            <TabsTrigger value="risks">
              <AlertTriangle className="w-4 h-4 mr-2" />
              风险辨识与措施管理 ({filteredCounts.risks})
            </TabsTrigger>
            <TabsTrigger value="emergencyMeasures">
              <Shield className="w-4 h-4 mr-2" />
              应急措施 ({filteredCounts.emergencyMeasures})
            </TabsTrigger>
            <TabsTrigger value="specs">
              <Settings className="w-4 h-4 mr-2" />
              规格参数
            </TabsTrigger>
          </TabsList>

          {/* 知识概览 */}
          <TabsContent value="overview" className="mt-4">
            <KnowledgeOverview
              templates={methodTemplates}
              standards={standards}
              safetyRiskPoints={riskPoints}
              emergencyMeasureTemplates={emergencyMeasureTemplates}
              qualityIssueTemplates={qualityIssueTemplates} // 传递质量通病数据（新增）
            />
          </TabsContent>

          {/* 施工方法模板 */}
          <TabsContent value="methods" className="space-y-4 mt-4">
            <MethodTemplates
              methodTemplates={methodTemplates}
              onSubmit={handleMethodTemplateSubmit}
              onDelete={handleDeleteMethodTemplate}
              onEnhance={handleEnhanceKnowledge}
              onCopy={handleCopyMethodTemplate}
              searchTerm={searchTerm}
              setSearchTerm={setSearchTerm}
              selectedScenario={selectedScenario}
              setSelectedScenario={setSelectedScenario}
              filteredCounts={filteredCounts}
              handleFilteredCountChange={handleFilteredCountChange}
            />
          </TabsContent>

          {/* 标准规范 */}
          <TabsContent value="standards" className="space-y-4 mt-4">
            <Standards
              standards={standards}
              onSubmit={handleSaveStandard}
              onDelete={handleDeleteStandard}
              searchTerm={searchTerm}
              setSearchTerm={setSearchTerm}
              handleFilteredCountChange={handleFilteredCountChange}
            />
          </TabsContent>

          {/* 风险辨识 */}
          <TabsContent value="risks" className="space-y-4 mt-4">
            <SafetyRisks
              riskPoints={riskPoints}
              onSave={handleSaveRiskPoint}
              onDelete={handleDeleteRiskPoint}
              onFilteredCountChange={handleRisksFilteredCountChange}
            />
          </TabsContent>

          {/* 应急措施 */}
          <TabsContent value="emergencyMeasures" className="space-y-4 mt-4">
            <EmergencyMeasureTemplateManager
              templates={emergencyMeasureTemplates}
              onSave={handleSaveEmergencyMeasureTemplate}
              onDelete={handleDeleteEmergencyMeasureTemplate}
              isLoading={isLoading}
              onFilteredCountChange={handleEmergencyMeasuresCountChange} // 使用缓存的回调
            />
          </TabsContent>

          {/* 规格参数 */}
          <TabsContent value="specs" className="space-y-4 mt-4">
            <SpecParameters />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
